/**
 * @file redis_comprehensive_test.cpp
 * @brief Redis模块全面测试
 * @author AI Assistant
 * @date 2025/7/10
 * 
 * 全面测试Redis连接池和线程池集成的功能和性能，包括：
 * - Redis连接基础功能测试
 * - 连接池管理测试
 * - 线程池集成测试
 * - 异步操作测试
 * - 性能压力测试
 * - 配置管理测试
 * - 错误处理测试
 * - 数据类型操作测试
 * - 事务和管道测试
 */

#include <iostream>
#include <chrono>
#include <thread>
#include <vector>
#include <future>
#include <atomic>
#include <random>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <map>
#include <set>

#include "common/database/redis_pool.h"
#include "common/config/config_manager.h"
#include "common/logger/logger.h"

using namespace common::database;
using namespace common::config;

class RedisComprehensiveTest {
private:
    std::atomic<int> test_count_{0};
    std::atomic<int> passed_count_{0};
    std::string redis_host_ = "redis";
    int redis_port_ = 6379;
    std::string redis_password_ = "123456";
    
    // 性能测试结果结构
    struct PerformanceResult {
        std::string test_name;
        double avg_time_ms;
        double min_time_ms;
        double max_time_ms;
        double throughput_ops_per_sec;
        size_t total_operations;
        size_t successful_operations;
        double success_rate;
    };
    
    std::vector<PerformanceResult> performance_results_;
    
    void recordTest(bool passed, const std::string& test_name) {
        test_count_++;
        if (passed) {
            passed_count_++;
            std::cout << "✓ " << test_name << std::endl;
        } else {
            std::cout << "✗ " << test_name << " - FAILED" << std::endl;
        }
    }
    
    void recordPerformance(const PerformanceResult& result) {
        performance_results_.push_back(result);
    }

public:
    void runAllTests() {
        std::cout << "=== Redis模块全面测试 ===" << std::endl;
        std::cout << "Redis服务器: " << redis_host_ << ":" << redis_port_ << std::endl;
        
        // 设置测试配置
        setupTestConfig();
        
        // 基础功能测试
        testBasicConfiguration();
        testConnectionPoolCreation();
        testConnectionManagement();
        
        // Redis连接功能测试
        testRedisConnectionBasics();
        testRedisDataTypes();
        testRedisTransactions();
        testRedisPipeline();
        
        // 线程池集成测试
        testThreadPoolIntegration();
        testAsyncOperations();
        testConcurrentOperations();
        
        // 性能测试
        testConnectionPoolPerformance();
        testRedisOperationPerformance();
        testAsyncPerformance();
        
        // 错误处理测试
        testErrorHandling();
        testConnectionFailures();
        testResourceLimits();
        
        // 配置管理测试
        testConfigHotReload();
        testConfigValidation();
        
        // 输出测试结果
        printTestResults();
        printPerformanceResults();
    }

private:
    void setupTestConfig() {
        std::cout << "\n=== 设置测试配置 ===" << std::endl;
        
        auto& config = ConfigManager::getInstance();
        
        // Redis基础配置
        config.set("database.redis.host", redis_host_);
        config.set("database.redis.port", std::to_string(redis_port_));
        config.set("database.redis.password", redis_password_);
        config.set("database.redis.database", "0");
        
        // 连接池配置
        config.set("database.redis.pool.initial_size", "3");
        config.set("database.redis.pool.max_size", "10");
        config.set("database.redis.pool.min_size", "1");
        config.set("database.redis.pool.idle_timeout", "300");
        config.set("database.redis.pool.health_check_interval", "30");
        
        // 线程池配置
        config.set("database.redis.thread_pool.enable_async_operations", "true");
        config.set("database.redis.thread_pool.core_size", "4");
        config.set("database.redis.thread_pool.max_size", "8");
        config.set("database.redis.thread_pool.keep_alive_ms", "60000");
        config.set("database.redis.thread_pool.queue_capacity", "1000");
        config.set("database.redis.thread_pool.enable_monitoring", "true");
        
        recordTest(true, "测试配置设置完成");
    }
    
    void testBasicConfiguration() {
        std::cout << "\n=== 测试基础配置 ===" << std::endl;
        
        try {
            // 测试配置验证
            RedisPool::redisConfig config;
            config.host = redis_host_;
            config.port = redis_port_;
            config.password = redis_password_;
            config.enable_async_operations = true;
            config.thread_pool_core_size = 4;
            config.thread_pool_max_size = 8;
            
            config.validate();
            recordTest(true, "配置验证通过");
            
            // 测试从ConfigManager加载配置
            auto loaded_config = RedisPool::redisConfig::fromConfigManager();
            bool config_loaded = (loaded_config.host == redis_host_ && 
                                loaded_config.port == redis_port_ &&
                                loaded_config.enable_async_operations == true);
            recordTest(config_loaded, "从ConfigManager加载配置");
            
        } catch (const std::exception& e) {
            recordTest(false, "配置测试异常: " + std::string(e.what()));
        }
    }
    
    void testConnectionPoolCreation() {
        std::cout << "\n=== 测试连接池创建 ===" << std::endl;
        
        try {
            // 创建连接池
            auto pool = std::make_unique<RedisPool>();
            recordTest(true, "连接池对象创建成功");
            
            // 启动连接池
            pool->start();
            recordTest(pool->isRunning(), "连接池启动成功");
            
            // 检查线程池集成
            bool async_enabled = pool->isAsyncOperationsEnabled();
            recordTest(async_enabled, "异步操作功能启用");
            
            // 获取状态信息
            std::string status = pool->getThreadPoolStatus();
            bool has_status = !status.empty() && status.find("线程池") != std::string::npos;
            recordTest(has_status, "线程池状态信息获取");
            
            // 关闭连接池
            pool->stop();
            recordTest(!pool->isRunning(), "连接池关闭成功");
            
        } catch (const std::exception& e) {
            recordTest(false, "连接池创建测试异常: " + std::string(e.what()));
        }
    }
    
    void testConnectionManagement() {
        std::cout << "\n=== 测试连接管理 ===" << std::endl;
        
        try {
            auto pool = std::make_unique<RedisPool>();
            pool->start();
            
            // 等待连接池初始化
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
            
            // 测试连接获取
            auto conn = pool->getConnection(std::chrono::milliseconds(1000));
            recordTest(conn != nullptr, "连接获取成功");
            
            if (conn) {
                // 测试连接状态
                recordTest(conn->getConnectionId().length() > 0, "连接ID生成");
                
                // 归还连接
                pool->returnConnection(conn);
                recordTest(true, "连接归还成功");
            }
            
            // 测试连接池统计
            size_t total = pool->getTotalConnections();
            size_t active = pool->getActiveConnections();
            size_t idle = pool->getIdleConnections();
            
            recordTest(total > 0, "总连接数统计: " + std::to_string(total));
            recordTest(active + idle == total, "连接数统计一致性");
            
            pool->stop();
            
        } catch (const std::exception& e) {
            recordTest(false, "连接管理测试异常: " + std::string(e.what()));
        }
    }

    void testRedisConnectionBasics() {
        std::cout << "\n=== 测试Redis连接基础功能 ===" << std::endl;

        try {
            auto pool = std::make_unique<RedisPool>();
            pool->start();
            std::this_thread::sleep_for(std::chrono::milliseconds(500));

            auto conn = pool->getConnection();
            if (!conn) {
                recordTest(false, "无法获取Redis连接");
                return;
            }

            // 测试连接状态
            recordTest(conn->isConnected(), "Redis连接状态检查");

            // 测试PING命令
            recordTest(conn->ping(), "Redis PING命令");

            // 测试基础字符串操作
            std::string test_key = "test:basic:key";
            std::string test_value = "Hello Redis!";

            recordTest(conn->set(test_key, test_value), "SET操作");

            std::string retrieved_value = conn->get(test_key);
            recordTest(retrieved_value == test_value, "GET操作");

            recordTest(conn->exists(test_key), "EXISTS操作");
            recordTest(conn->del(test_key), "DEL操作");
            recordTest(!conn->exists(test_key), "删除后EXISTS检查");

            // 测试TTL操作
            conn->set("test:ttl", "value", 10);
            recordTest(conn->ttl("test:ttl") > 0, "TTL设置和查询");

            // 测试数值操作
            conn->set("test:counter", "0");
            recordTest(conn->incr("test:counter") == 1, "INCR操作");
            recordTest(conn->decr("test:counter") == 0, "DECR操作");

            pool->returnConnection(conn);
            pool->stop();

        } catch (const std::exception& e) {
            recordTest(false, "Redis连接基础功能测试异常: " + std::string(e.what()));
        }
    }

    void testRedisDataTypes() {
        std::cout << "\n=== 测试Redis数据类型操作 ===" << std::endl;

        try {
            auto pool = std::make_unique<RedisPool>();
            pool->start();
            std::this_thread::sleep_for(std::chrono::milliseconds(500));

            auto conn = pool->getConnection();
            if (!conn) {
                recordTest(false, "无法获取Redis连接");
                return;
            }

            // 测试Hash操作
            std::string hash_key = "test:hash";
            recordTest(conn->hset(hash_key, "field1", "value1"), "HSET操作");
            recordTest(conn->hget(hash_key, "field1") == "value1", "HGET操作");
            recordTest(conn->hexists(hash_key, "field1"), "HEXISTS操作");

            conn->hset(hash_key, "field2", "value2");
            auto hash_keys = conn->hkeys(hash_key);
            recordTest(hash_keys.size() == 2, "HKEYS操作");

            auto hash_values = conn->hvals(hash_key);
            recordTest(hash_values.size() == 2, "HVALS操作");

            auto hash_all = conn->hgetall(hash_key);
            recordTest(hash_all.size() == 2, "HGETALL操作");

            recordTest(conn->hdel(hash_key, "field1"), "HDEL操作");

            // 测试List操作
            std::string list_key = "test:list";
            recordTest(conn->lpush(list_key, "item1") > 0, "LPUSH操作");
            recordTest(conn->rpush(list_key, "item2") > 0, "RPUSH操作");
            recordTest(conn->llen(list_key) == 2, "LLEN操作");

            std::string popped = conn->lpop(list_key);
            recordTest(!popped.empty(), "LPOP操作");

            popped = conn->rpop(list_key);
            recordTest(!popped.empty(), "RPOP操作");

            // 测试Set操作
            std::string set_key = "test:set";
            recordTest(conn->sadd(set_key, "member1"), "SADD操作");
            recordTest(conn->sismember(set_key, "member1"), "SISMEMBER操作");
            recordTest(conn->scard(set_key) == 1, "SCARD操作");

            conn->sadd(set_key, "member2");
            auto set_members = conn->smembers(set_key);
            recordTest(set_members.size() == 2, "SMEMBERS操作");

            recordTest(conn->srem(set_key, "member1"), "SREM操作");

            // 测试Sorted Set操作
            std::string zset_key = "test:zset";
            recordTest(conn->zadd(zset_key, 1.0, "member1"), "ZADD操作");
            recordTest(conn->zadd(zset_key, 2.0, "member2"), "ZADD多个成员");
            recordTest(conn->zcard(zset_key) == 2, "ZCARD操作");

            double score = conn->zscore(zset_key, "member1");
            recordTest(score == 1.0, "ZSCORE操作");

            auto zrange_result = conn->zrange(zset_key, 0, -1);
            recordTest(zrange_result.size() == 2, "ZRANGE操作");

            auto zrevrange_result = conn->zrevrange(zset_key, 0, -1);
            recordTest(zrevrange_result.size() == 2, "ZREVRANGE操作");

            recordTest(conn->zrem(zset_key, "member1"), "ZREM操作");

            pool->returnConnection(conn);
            pool->stop();

        } catch (const std::exception& e) {
            recordTest(false, "Redis数据类型测试异常: " + std::string(e.what()));
        }
    }

    void testRedisTransactions() {
        std::cout << "\n=== 测试Redis事务操作 ===" << std::endl;

        try {
            auto pool = std::make_unique<RedisPool>();
            pool->start();
            std::this_thread::sleep_for(std::chrono::milliseconds(500));

            auto conn = pool->getConnection();
            if (!conn) {
                recordTest(false, "无法获取Redis连接");
                return;
            }

            // 测试基础事务
            recordTest(conn->multi(), "MULTI命令");

            // 在事务中执行命令
            conn->set("tx:key1", "value1");
            conn->set("tx:key2", "value2");
            conn->incr("tx:counter");

            // 执行事务
            auto results = conn->exec();
            recordTest(!results.empty(), "EXEC命令执行");

            // 清理结果
            for (auto* reply : results) {
                if (reply) conn->freeReply(reply);
            }

            // 验证事务结果
            recordTest(conn->get("tx:key1") == "value1", "事务中SET命令生效");
            recordTest(conn->get("tx:key2") == "value2", "事务中多个命令生效");

            // 测试事务取消
            recordTest(conn->multi(), "第二个MULTI命令");
            conn->set("tx:key3", "value3");
            recordTest(conn->discard(), "DISCARD命令");
            recordTest(!conn->exists("tx:key3"), "DISCARD后命令未执行");

            pool->returnConnection(conn);
            pool->stop();

        } catch (const std::exception& e) {
            recordTest(false, "Redis事务测试异常: " + std::string(e.what()));
        }
    }

    void testRedisPipeline() {
        std::cout << "\n=== 测试Redis管道操作 ===" << std::endl;

        try {
            auto pool = std::make_unique<RedisPool>();
            pool->start();
            std::this_thread::sleep_for(std::chrono::milliseconds(500));

            auto conn = pool->getConnection();
            if (!conn) {
                recordTest(false, "无法获取Redis连接");
                return;
            }

            // 测试管道基础功能
            conn->pipelineStart();
            recordTest(conn->isPipelineActive(), "管道模式启动");

            // 添加命令到管道
            conn->pipelineAddSet("pipe:key1", "value1");
            conn->pipelineAddSet("pipe:key2", "value2");
            conn->pipelineAddGet("pipe:key1");
            conn->pipelineAddDel("pipe:key2");

            recordTest(conn->getPipelineCommandCount() == 4, "管道命令计数");

            // 执行管道
            auto pipeline_results = conn->pipelineExec();
            recordTest(!pipeline_results.empty(), "管道执行");
            recordTest(!conn->isPipelineActive(), "管道执行后状态重置");

            // 清理管道结果
            for (auto* reply : pipeline_results) {
                if (reply) conn->freeReply(reply);
            }

            // 测试管道取消
            conn->pipelineStart();
            conn->pipelineAdd("SET pipe:key3 value3");
            conn->PipelineDiscard();
            recordTest(!conn->isPipelineActive(), "管道取消功能");
            recordTest(conn->getPipelineCommandCount() == 0, "管道取消后命令清空");

            pool->returnConnection(conn);
            pool->stop();

        } catch (const std::exception& e) {
            recordTest(false, "Redis管道测试异常: " + std::string(e.what()));
        }
    }

    void testThreadPoolIntegration() {
        std::cout << "\n=== 测试线程池集成 ===" << std::endl;

        try {
            auto pool = std::make_unique<RedisPool>();
            pool->start();
            std::this_thread::sleep_for(std::chrono::milliseconds(500));

            // 测试线程池初始化
            recordTest(pool->isAsyncOperationsEnabled(), "异步操作启用检查");

            // 测试线程池状态获取
            std::string status = pool->getThreadPoolStatus();
            bool has_thread_info = status.find("线程池") != std::string::npos;
            recordTest(has_thread_info, "线程池状态信息获取");

            if (has_thread_info) {
                std::cout << "   线程池状态详情:\n" << status << std::endl;
            }

            // 测试线程池关闭和重启
            pool->shutdownThreadPool();
            recordTest(pool->getThreadPoolStatus().find("未初始化") != std::string::npos, "线程池关闭");

            pool->initializeThreadPool();
            recordTest(pool->isAsyncOperationsEnabled(), "线程池重新初始化");

            pool->stop();

        } catch (const std::exception& e) {
            recordTest(false, "线程池集成测试异常: " + std::string(e.what()));
        }
    }

    void testAsyncOperations() {
        std::cout << "\n=== 测试异步操作 ===" << std::endl;

        try {
            auto pool = std::make_unique<RedisPool>();
            pool->start();
            std::this_thread::sleep_for(std::chrono::milliseconds(500));

            if (!pool->isAsyncOperationsEnabled()) {
                recordTest(false, "异步操作未启用，跳过测试");
                return;
            }

            // 测试异步连接创建
            auto future_connections = pool->createConnectionsAsync(3);

            // 测试异步健康检查
            pool->performAsyncHealthCheck();
            recordTest(true, "异步健康检查调用");

            // 测试异步连接清理
            pool->cleanupExpiredConnectionsAsync();
            recordTest(true, "异步连接清理调用");

            // 测试异步预热
            pool->warmupPoolAsync(5);
            recordTest(true, "异步预热调用");

            // 等待异步连接创建完成
            try {
                auto connections = future_connections.get();
                recordTest(true, "异步连接创建完成，创建数量: " + std::to_string(connections.size()));
            } catch (const std::exception& e) {
                recordTest(false, "异步连接创建异常: " + std::string(e.what()));
            }

            // 等待其他异步操作完成
            std::this_thread::sleep_for(std::chrono::seconds(2));

            pool->stop();

        } catch (const std::exception& e) {
            recordTest(false, "异步操作测试异常: " + std::string(e.what()));
        }
    }

    void testConcurrentOperations() {
        std::cout << "\n=== 测试并发操作 ===" << std::endl;

        try {
            auto pool = std::make_unique<RedisPool>();
            pool->start();
            std::this_thread::sleep_for(std::chrono::milliseconds(500));

            const int thread_count = 5;
            const int ops_per_thread = 20;
            std::vector<std::future<int>> futures;
            std::atomic<int> total_success{0};

            // 启动多个线程进行并发操作
            for (int t = 0; t < thread_count; ++t) {
                auto future = std::async(std::launch::async, [&pool, ops_per_thread, t]() {
                    int success_count = 0;
                    for (int i = 0; i < ops_per_thread; ++i) {
                        try {
                            auto conn = pool->getConnection(std::chrono::milliseconds(1000));
                            if (conn) {
                                std::string key = "concurrent:thread" + std::to_string(t) + ":op" + std::to_string(i);
                                std::string value = "value_" + std::to_string(i);

                                if (conn->set(key, value) && conn->get(key) == value) {
                                    success_count++;
                                }

                                pool->returnConnection(conn);
                            }
                        } catch (...) {
                            // 忽略异常，继续测试
                        }
                    }
                    return success_count;
                });
                futures.push_back(std::move(future));
            }

            // 收集结果
            for (auto& future : futures) {
                total_success += future.get();
            }

            int expected_total = thread_count * ops_per_thread;
            double success_rate = (double)total_success.load() / expected_total * 100.0;

            recordTest(success_rate > 80.0, "并发操作成功率: " +
                      std::to_string(success_rate) + "% (" +
                      std::to_string(total_success.load()) + "/" +
                      std::to_string(expected_total) + ")");

            pool->stop();

        } catch (const std::exception& e) {
            recordTest(false, "并发操作测试异常: " + std::string(e.what()));
        }
    }

    void testConnectionPoolPerformance() {
        std::cout << "\n=== 测试连接池性能 ===" << std::endl;

        try {
            auto pool = std::make_unique<RedisPool>();
            pool->start();
            std::this_thread::sleep_for(std::chrono::milliseconds(500));

            const int iterations = 1000;
            std::vector<double> times;
            times.reserve(iterations);

            auto start_time = std::chrono::high_resolution_clock::now();
            int successful_ops = 0;

            for (int i = 0; i < iterations; ++i) {
                auto op_start = std::chrono::high_resolution_clock::now();

                try {
                    auto conn = pool->getConnection(std::chrono::milliseconds(100));
                    if (conn) {
                        pool->returnConnection(conn);
                        successful_ops++;
                    }
                } catch (...) {
                    // 忽略异常
                }

                auto op_end = std::chrono::high_resolution_clock::now();
                auto duration = std::chrono::duration<double, std::milli>(op_end - op_start);
                times.push_back(duration.count());
            }

            auto end_time = std::chrono::high_resolution_clock::now();
            auto total_duration = std::chrono::duration<double>(end_time - start_time);

            if (!times.empty()) {
                std::sort(times.begin(), times.end());

                PerformanceResult result;
                result.test_name = "连接池获取/归还";
                result.total_operations = iterations;
                result.successful_operations = successful_ops;
                result.success_rate = (double)successful_ops / iterations * 100.0;
                result.avg_time_ms = std::accumulate(times.begin(), times.end(), 0.0) / times.size();
                result.min_time_ms = times.front();
                result.max_time_ms = times.back();
                result.throughput_ops_per_sec = successful_ops / total_duration.count();

                recordPerformance(result);
                recordTest(result.success_rate > 95.0, "连接池性能测试完成");
            }

            pool->stop();

        } catch (const std::exception& e) {
            recordTest(false, "连接池性能测试异常: " + std::string(e.what()));
        }
    }

    void testRedisOperationPerformance() {
        std::cout << "\n=== 测试Redis操作性能 ===" << std::endl;

        try {
            auto pool = std::make_unique<RedisPool>();
            pool->start();
            std::this_thread::sleep_for(std::chrono::milliseconds(500));

            auto conn = pool->getConnection();
            if (!conn) {
                recordTest(false, "无法获取连接进行性能测试");
                return;
            }

            // 测试SET操作性能
            const int set_iterations = 1000;
            auto set_start = std::chrono::high_resolution_clock::now();
            int set_success = 0;

            for (int i = 0; i < set_iterations; ++i) {
                std::string key = "perf:set:" + std::to_string(i);
                std::string value = "value_" + std::to_string(i);
                if (conn->set(key, value)) {
                    set_success++;
                }
            }

            auto set_end = std::chrono::high_resolution_clock::now();
            auto set_duration = std::chrono::duration<double>(set_end - set_start);

            PerformanceResult set_result;
            set_result.test_name = "Redis SET操作";
            set_result.total_operations = set_iterations;
            set_result.successful_operations = set_success;
            set_result.success_rate = (double)set_success / set_iterations * 100.0;
            set_result.avg_time_ms = set_duration.count() * 1000.0 / set_iterations;
            set_result.throughput_ops_per_sec = set_success / set_duration.count();

            recordPerformance(set_result);

            // 测试GET操作性能
            const int get_iterations = 1000;
            auto get_start = std::chrono::high_resolution_clock::now();
            int get_success = 0;

            for (int i = 0; i < get_iterations; ++i) {
                std::string key = "perf:set:" + std::to_string(i % set_success);
                std::string value = conn->get(key);
                if (!value.empty()) {
                    get_success++;
                }
            }

            auto get_end = std::chrono::high_resolution_clock::now();
            auto get_duration = std::chrono::duration<double>(get_end - get_start);

            PerformanceResult get_result;
            get_result.test_name = "Redis GET操作";
            get_result.total_operations = get_iterations;
            get_result.successful_operations = get_success;
            get_result.success_rate = (double)get_success / get_iterations * 100.0;
            get_result.avg_time_ms = get_duration.count() * 1000.0 / get_iterations;
            get_result.throughput_ops_per_sec = get_success / get_duration.count();

            recordPerformance(get_result);

            recordTest(set_result.success_rate > 95.0 && get_result.success_rate > 95.0,
                      "Redis操作性能测试完成");

            pool->returnConnection(conn);
            pool->stop();

        } catch (const std::exception& e) {
            recordTest(false, "Redis操作性能测试异常: " + std::string(e.what()));
        }
    }

    void testAsyncPerformance() {
        std::cout << "\n=== 测试异步操作性能 ===" << std::endl;

        try {
            auto pool = std::make_unique<RedisPool>();
            pool->start();
            std::this_thread::sleep_for(std::chrono::milliseconds(500));

            if (!pool->isAsyncOperationsEnabled()) {
                recordTest(false, "异步操作未启用，跳过性能测试");
                return;
            }

            // 测试异步连接创建性能
            const int async_tests = 10;
            std::vector<double> async_times;

            for (int i = 0; i < async_tests; ++i) {
                auto start = std::chrono::high_resolution_clock::now();

                auto future = pool->createConnectionsAsync(3);
                auto status = future.wait_for(std::chrono::seconds(2));

                if (status == std::future_status::ready) {
                    auto connections = future.get();
                    auto end = std::chrono::high_resolution_clock::now();
                    auto duration = std::chrono::duration<double, std::milli>(end - start);
                    async_times.push_back(duration.count());
                }
            }

            if (!async_times.empty()) {
                double avg_time = std::accumulate(async_times.begin(), async_times.end(), 0.0) / async_times.size();
                recordTest(avg_time < 1000.0, "异步连接创建平均耗时: " +
                          std::to_string(avg_time) + "ms");
            }

            pool->stop();

        } catch (const std::exception& e) {
            recordTest(false, "异步性能测试异常: " + std::string(e.what()));
        }
    }

    void testErrorHandling() {
        std::cout << "\n=== 测试错误处理 ===" << std::endl;

        try {
            // 测试无效配置
            try {
                RedisPool::redisConfig invalid_config;
                invalid_config.host = "";  // 无效主机
                invalid_config.validate();
                recordTest(false, "无效配置应该抛出异常");
            } catch (const std::exception&) {
                recordTest(true, "无效主机配置正确抛出异常");
            }

            try {
                RedisPool::redisConfig invalid_config;
                invalid_config.port = 0;  // 无效端口
                invalid_config.validate();
                recordTest(false, "无效端口应该抛出异常");
            } catch (const std::exception&) {
                recordTest(true, "无效端口配置正确抛出异常");
            }

            try {
                RedisPool::redisConfig invalid_config;
                invalid_config.enable_async_operations = true;
                invalid_config.thread_pool_core_size = 0;  // 无效线程池配置
                invalid_config.validate();
                recordTest(false, "无效线程池配置应该抛出异常");
            } catch (const std::exception&) {
                recordTest(true, "无效线程池配置正确抛出异常");
            }

        } catch (const std::exception& e) {
            recordTest(false, "错误处理测试异常: " + std::string(e.what()));
        }
    }

    void testConnectionFailures() {
        std::cout << "\n=== 测试连接失败处理 ===" << std::endl;

        try {
            // 测试连接到不存在的服务器
            RedisPool::redisConfig config;
            config.host = "nonexistent-redis-server";
            config.port = 6379;
            config.enable_async_operations = false;  // 禁用异步操作以简化测试

            auto pool = std::make_unique<RedisPool>(config);
            pool->start();

            // 等待连接尝试
            std::this_thread::sleep_for(std::chrono::milliseconds(1000));

            // 尝试获取连接（应该失败或超时）
            auto conn = pool->getConnection(std::chrono::milliseconds(500));
            recordTest(conn == nullptr, "不存在服务器连接正确失败");

            pool->stop();

        } catch (const std::exception& e) {
            recordTest(true, "连接失败正确处理异常: " + std::string(e.what()));
        }
    }

    void testResourceLimits() {
        std::cout << "\n=== 测试资源限制 ===" << std::endl;

        try {
            RedisPool::redisConfig config;
            config.host = redis_host_;
            config.port = redis_port_;
            config.initial_size = 1;
            config.max_size = 2;  // 很小的连接池
            config.enable_async_operations = false;

            auto pool = std::make_unique<RedisPool>(config);
            pool->start();
            std::this_thread::sleep_for(std::chrono::milliseconds(500));

            // 尝试获取超过最大连接数的连接
            std::vector<std::shared_ptr<RedisConnection>> connections;

            for (int i = 0; i < 5; ++i) {  // 尝试获取5个连接，但最大只有2个
                auto conn = pool->getConnection(std::chrono::milliseconds(100));
                if (conn) {
                    connections.push_back(conn);
                }
            }

            // 应该最多获取到max_size个连接
            bool resource_limit_respected = connections.size() <= config.max_size;
            recordTest(resource_limit_respected, "连接池资源限制得到尊重，获取到 " +
                      std::to_string(connections.size()) + " 个连接");

            // 归还连接
            for (auto& conn : connections) {
                pool->returnConnection(conn);
            }

            pool->stop();

        } catch (const std::exception& e) {
            recordTest(false, "资源限制测试异常: " + std::string(e.what()));
        }
    }

    void testConfigHotReload() {
        std::cout << "\n=== 测试配置热更新 ===" << std::endl;

        try {
            auto pool = std::make_unique<RedisPool>();
            pool->start();
            pool->enableConfigHotReload();
            recordTest(true, "配置热更新监听启用");

            auto& config = ConfigManager::getInstance();

            // 测试线程池配置变更
            std::string old_core_size = config.get<std::string>("database.redis.thread_pool.core_size", "4");
            config.set("database.redis.thread_pool.core_size", "6");

            // 等待配置变更处理
            std::this_thread::sleep_for(std::chrono::milliseconds(500));

            // 恢复原配置
            config.set("database.redis.thread_pool.core_size", old_core_size);

            recordTest(true, "配置热更新测试完成");

            pool->stop();

        } catch (const std::exception& e) {
            recordTest(false, "配置热更新测试异常: " + std::string(e.what()));
        }
    }

    void testConfigValidation() {
        std::cout << "\n=== 测试配置验证 ===" << std::endl;

        try {
            // 测试各种配置组合
            RedisPool::redisConfig config;

            // 测试正常配置
            config.host = "localhost";
            config.port = 6379;
            config.enable_async_operations = true;
            config.thread_pool_core_size = 4;
            config.thread_pool_max_size = 8;
            config.thread_pool_queue_capacity = 1000;

            config.validate();
            recordTest(true, "正常配置验证通过");

            // 测试边界值
            config.thread_pool_core_size = 1;
            config.thread_pool_max_size = 1;
            config.validate();
            recordTest(true, "边界值配置验证通过");

        } catch (const std::exception& e) {
            recordTest(false, "配置验证测试异常: " + std::string(e.what()));
        }
    }

    void printTestResults() {
        std::cout << "\n=== 测试结果总结 ===" << std::endl;
        std::cout << "总测试数: " << test_count_.load() << std::endl;
        std::cout << "通过测试: " << passed_count_.load() << std::endl;
        std::cout << "失败测试: " << (test_count_.load() - passed_count_.load()) << std::endl;

        double pass_rate = (double)passed_count_.load() / test_count_.load() * 100.0;
        std::cout << "通过率: " << std::fixed << std::setprecision(1) << pass_rate << "%" << std::endl;

        if (pass_rate >= 95.0) {
            std::cout << "🎉 测试结果: 优秀" << std::endl;
        } else if (pass_rate >= 80.0) {
            std::cout << "✅ 测试结果: 良好" << std::endl;
        } else {
            std::cout << "⚠️  测试结果: 需要改进" << std::endl;
        }

        std::cout << "\n💡 测试说明:" << std::endl;
        std::cout << "  - Redis连接测试可能因为服务器不可达而失败，这是正常的" << std::endl;
        std::cout << "  - 重点关注连接池管理、线程池集成和异步操作功能" << std::endl;
        std::cout << "  - 性能测试结果受网络延迟和服务器性能影响" << std::endl;
        std::cout << "  - 在生产环境中请确保Redis服务器配置正确" << std::endl;
    }

    void printPerformanceResults() {
        if (performance_results_.empty()) {
            return;
        }

        std::cout << "\n=== 性能测试结果 ===" << std::endl;
        std::cout << std::left << std::setw(20) << "测试项目"
                  << std::setw(12) << "平均耗时(ms)"
                  << std::setw(15) << "吞吐量(ops/s)"
                  << std::setw(12) << "成功率(%)"
                  << std::setw(12) << "总操作数" << std::endl;
        std::cout << std::string(80, '-') << std::endl;

        for (const auto& result : performance_results_) {
            std::cout << std::left << std::setw(20) << result.test_name
                      << std::setw(12) << std::fixed << std::setprecision(3) << result.avg_time_ms
                      << std::setw(15) << std::fixed << std::setprecision(1) << result.throughput_ops_per_sec
                      << std::setw(12) << std::fixed << std::setprecision(1) << result.success_rate
                      << std::setw(12) << result.total_operations << std::endl;
        }

        std::cout << "\n💡 性能测试说明:" << std::endl;
        std::cout << "  - 测试结果可能受到网络延迟和Redis服务器性能影响" << std::endl;
        std::cout << "  - 在生产环境中，请根据实际负载调整连接池和线程池配置" << std::endl;
        std::cout << "  - 建议定期运行性能测试以监控系统性能变化" << std::endl;
    }
};

int main() {
    try {
        RedisComprehensiveTest test;
        test.runAllTests();
        return 0;
    } catch (const std::exception& e) {
        std::cerr << "测试程序异常: " << e.what() << std::endl;
        return 1;
    }
}
